﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection;

namespace teach
{
    public class QuestionType
    {
        private List<QuestionItem> m_questionsItems = new List<QuestionItem>();

        public string Name { get; set; }
        public string UI { get; set; }


        public Question GetNewQuestion(string userName)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Question question = Activator.CreateInstance(assembly.GetType("teach." + Name)) as Question;
            question.QuestionType = this.Name;

            if (m_questionsItems.Count > 0)
            {
                question.Properties = m_questionsItems[TeachController.RND.Next(m_questionsItems.Count)].Properties;
                while (question.Properties["kids"].ToLower() != "both" && question.Properties["kids"].ToLower() != "all" && question.Properties["kids"].ToLower() != userName.ToLower())
                {
                    question.Properties = m_questionsItems[TeachController.RND.Next(m_questionsItems.Count)].Properties;
                }
            }
            return question;
        }

        public void LoadProperties(string path)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNodeList itemList = doc.DocumentElement.SelectNodes("item");
                foreach (XmlNode node in itemList)
                {
                    QuestionItem questionItem = new QuestionItem();
                    XmlNodeList properties = node.ChildNodes;
                    foreach (XmlNode property in properties)
                    {
                        questionItem.Properties[property.Name] = property.InnerText;
                    }
                    questionItem.Kids = questionItem.Properties["kids"];
                    questionItem.Weight = int.Parse(questionItem.Properties["weight"]);
                    for (int i = 0; i < questionItem.Weight; i++)
                    {
                        m_questionsItems.Add(questionItem);
                    }
                }
            }
            catch (Exception ex)
            {
                TeachController.LogError("QuestionType.LoadProperties(" + path + ")", ex);
                throw ex;
            }
        }

    }
}
